namespace Testcontainers.Elasticsearch;

public abstract class ElasticsearchContainerTest : IAsyncLifetime
{
    private readonly ElasticsearchContainer _elasticsearchContainer;

    private ElasticsearchContainerTest(ElasticsearchContainer elasticsearchContainer)
    {
        _elasticsearchContainer = elasticsearchContainer;
    }

    // # --8<-- [start:UseElasticsearchContainer]
    public async ValueTask InitializeAsync()
    {
        await _elasticsearchContainer.StartAsync()
            .ConfigureAwait(false);
    }

    public async ValueTask DisposeAsync()
    {
        await DisposeAsyncCore()
            .ConfigureAwait(false);

        GC.SuppressFinalize(this);
    }

    [Fact]
    [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))]
    public void PingReturnsValidResponse()
    {
        // Given
        var clientSettings = new ElasticsearchClientSettings(new Uri(_elasticsearchContainer.GetConnectionString()));
        clientSettings.ServerCertificateValidationCallback(CertificateValidations.AllowAll);

        var client = new ElasticsearchClient(clientSettings);

        // When
        var response = client.Ping();

        // Then
        Assert.True(response.IsValidResponse);
    }
    // # --8<-- [end:UseElasticsearchContainer]

    protected virtual ValueTask DisposeAsyncCore()
    {
        return _elasticsearchContainer.DisposeAsync();
    }

    // # --8<-- [start:CreateElasticsearchContainer]
    [UsedImplicitly]
    public sealed class ElasticsearchDefaultConfiguration : ElasticsearchContainerTest
    {
        public ElasticsearchDefaultConfiguration()
            : base(new ElasticsearchBuilder(TestSession.GetImageFromDockerfile()).Build())
        {
        }
    }

    [UsedImplicitly]
    public sealed class ElasticsearchAuthConfiguration : ElasticsearchContainerTest
    {
        public ElasticsearchAuthConfiguration()
            : base(new ElasticsearchBuilder(TestSession.GetImageFromDockerfile()).WithPassword("some-password").Build())
        {
        }
    }
    // # --8<-- [end:CreateElasticsearchContainer]
}